package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.model.MyAccessToken;
import com.example.demo.model.User;
import com.example.demo.model.UserToken;
import com.example.demo.service.MyAccessTokenService;
import com.example.demo.service.UserService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@Controller
@RequestMapping("/myoauth")
public class MyOauth2Controller {
	
	@Autowired
	private MyAccessTokenService myAccessTokenService;
	@Autowired
	private UserService userService;
	
    @GetMapping("/check_token")
    @ResponseBody
    public Object checkToken(@RequestParam(value = "token") String token){
    	Map<String,Object> result = new HashMap<String, Object>();
    	result.put("status", 0);
    	UserToken queryUserToken = new UserToken();
    	queryUserToken.setAccess_token(token);
    	try {
    		MyAccessToken myAccessToken = myAccessTokenService.selectByPrimaryKey(token);
    		result.put("message", myAccessToken);
		} catch (Exception e) {
			result.put("status", 1);
			result.put("message", "请求失败，"+e.getMessage());
		}
        return result;
    }

	/*
	 	url格式
		https://oauth.b.com/token?
			  grant_type=password&
			  username=USERNAME&
			  password=PASSWORD&
			  client_id=CLIENT_ID
			  上面 URL 中，grant_type参数是授权方式，这里的password表示"密码式"，username和password是用户名和密码
		access_token格式
		{
		"access_token": "b90c7863-2f92-4118-85ca-77b995f0677a",
		"token_type": "bearer",
		"refresh_token": "917e7237-3e0a-4aef-98a2-ada256b5eaef",
		"expires_in": 43199,
		"scope": "all"
		}
    */
    @ApiOperation(value = "密码模式获取token",notes = "根据userAccount、password进行登录认证并返回token")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "userAccount",value = "用户登录账号",required = true,dataType = "String",paramType = "query"),
    	@ApiImplicitParam(name = "password",value = "用户登录密码",required = true,dataType = "String",paramType = "query")
    })
	@PostMapping("/token")
	@ResponseBody
	public Object token(@RequestParam(value = "userAccount",required = false,defaultValue = "admin") String userAccount,
			@RequestParam(value = "password",required = false,defaultValue = "123456") String password,
			@RequestParam(value = "grant_type",required = true,defaultValue = "password") String grant_type,
			@RequestParam(value = "client_id",required = true,defaultValue = "client_id") String client_id,
			@RequestParam(value = "scope",required = false,defaultValue = "all") String scope
			) {
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("status", 0);
		try {
			if(!"password".equals(grant_type)) {
				throw new Exception("grant_type支持password模式");
			}
			if(!"client_id".equals(client_id)) {
				throw new Exception("非法的client_id");
			}
			//userAccount和password非空验证
			if(StringUtils.isEmpty(userAccount) || StringUtils.isEmpty(password)) {
				throw new Exception("账号密码不能为空");
			}
			
			//验证userAccount和password是否匹配
			User user = userService.selectByPrimaryKey(userAccount);
			if (user == null) {
				throw new Exception("账号不存在");
			}
			if(!password.equals(user.getPassword())) {
				throw new Exception("账号与密码不匹配");
			}
			
			//生成对应的userAccount的AccessToken
			String randomUUID = UUID.randomUUID().toString();
			MyAccessToken myAccessToken = new MyAccessToken();
			myAccessToken.setAccess_token(randomUUID);
			myAccessToken.setUserAccount(userAccount);
			myAccessToken.setScope(scope);
			result.put("message", myAccessToken);
			//将对应的username的AccessToken保存至服务器
			//...
			//重新申请accessTolen之后需要将旧的数据清除掉
			//...
			//将myAccessToken入库
//			myAccessTokenService.insert(myAccessToken);
			myAccessTokenService.create(myAccessToken);
//			return myAccessToken;
		} catch (Exception e) {
//			e.printStackTrace();
			result.put("status", 1);
			result.put("message", "请求失败，"+e.getMessage());
		}
		return result;
	}
	
	@ApiIgnore
	@GetMapping("/hello")
	@ResponseBody
	public Object g() {
		return myAccessTokenService.findAll();
	}
}
